package com.qiantoon.networkdsl.base;

import java.util.List;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;

/**
 * @Package com.qiantoon.network.base
 * @ClassName IMoreUrlInfo
 * @Author caostgrace
 * @Date 2021/4/12
 * @Email liaobing@qiantoon.com
 * @Desc
 */
public interface IMoreUrlInfo {
    String MORE_URL_HEADER_NAME = "more_url_header_name";
    String URL = "http://%s:%s/QiantoonService/";

    /**
     * 默认的多BaseUrl拦截器
     * @return
     */
    default Interceptor moreBaseUrlInterceptor(){
        return chain->{
            //获取原始的originalRequest
            Request originalRequest = chain.request();
            //获取老的url
            HttpUrl oldUrl = originalRequest.url();
            //获取originalRequest的创建者builder
            Request.Builder builder = originalRequest.newBuilder();
            //获取头信息的集合如：manage,mdffx
            List<String> moreUrlList = originalRequest.headers(MORE_URL_HEADER_NAME);
            if (moreUrlList.size() > 0) {
                //删除原有配置中的值,就是namesAndValues集合里的值
                builder.removeHeader(MORE_URL_HEADER_NAME);
                //获取头信息中配置的value,如：manage或者mdffx
                String urlMappingName = moreUrlList.get(0);
                HttpUrl baseURL;
                if(isSupport(urlMappingName)){
                    baseURL = HttpUrl.parse(convertUrl(urlMappingName));
                }else {
                    return chain.proceed(originalRequest);
                }
                if(baseURL == null){
                    return chain.proceed(originalRequest);
                }
                //重建新的HttpUrl，需要重新设置的url部分
                HttpUrl newHttpUrl = oldUrl.newBuilder()
                        .scheme(baseURL.scheme())//http协议如：http或者https
                        .host(baseURL.host())//主机地址
                        .port(baseURL.port())//端口
                        .build();
                //获取处理后的新newRequest
                Request newRequest = builder.url(newHttpUrl).build();
                return  chain.proceed(newRequest);
            }else{
                return chain.proceed(originalRequest);
            }
        };
    }

    /**
     * 是否支持此url映射
     * @param urlMappingName
     * @return
     */
    boolean isSupport(String urlMappingName);

    /**
     * 映射名转换为url
     * @param urlMappingName
     * @return
     */
    String convertUrl(String urlMappingName);


    default String urlFormat(String url, String port) {
        return String.format(URL, url, port);
    }
    
}
